package ynu.edu.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求路径
        String path = exchange.getRequest().getURI().getPath();
        
        // 如果是登录接口，直接放行
        if (path.contains("/login") || path.contains("/register")) {
            return chain.filter(exchange);
        }

        // 获取token
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        
        // 验证token
        if (token == null || token.isEmpty()) {
            // 设置响应状态码为401
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        if (!isValidToken(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        // token验证通过，继续执行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        // 过滤器优先级，数字越小优先级越高
        return 0;
    }

    private boolean isValidToken(String token) {
        // 这里实现token验证逻辑
        // 示例：简单判断token是否以"Bearer "开头
        return token.startsWith("Bearer ");
    }
} 